<template>
  <!-- 背景与双列布局：左侧品牌与技术栈，右侧半透明登录表单 -->
  <div class="login-bg">
    <div class="login-wrap">
      <!-- 左侧品牌与技术栈标签 -->
      <section class="branding">
        <div class="brand-logo">
          <el-icon class="logo-icon"><Cherry /></el-icon>
          <div class="brand-name">Drp 后台管理系统</div>
        </div>
        <p class="brand-desc">欢迎使用 Drp 后台管理系统</p>
        <div class="tech-tags">
          <el-tag type="success" effect="dark">Spring Boot</el-tag>
          <el-tag type="warning" effect="dark">MyBatis-Plus</el-tag>
          <el-tag type="info" effect="dark">Vue 3</el-tag>
          <el-tag type="primary" effect="dark">Element Plus</el-tag>
        </div>
      </section>

      <!-- 右侧半透明登录卡片 -->
      <section class="form-area">
        <el-card class="login-card" shadow="hover">
          <h2 class="title">后台管理系统登录</h2>
          <el-form :model="form" :rules="rules" ref="formRef" label-width="86px">
            <!-- 用户名输入，带图标 -->
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" clearable>
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <!-- 密码输入，带图标 -->
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password>
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <!-- 验证码输入与图片（Canvas） -->
            <el-form-item label="验证码" prop="captchaInput">
              <div class="captcha-row">
                <el-input v-model="form.captchaInput" placeholder="请输入右侧验证码" />
                <canvas ref="captchaRef" class="captcha-canvas" width="120" height="40" @click="refreshCaptcha" title="点击刷新验证码"></canvas>
              </div>
            </el-form-item>

            <!-- 记住我复选框 -->
            <el-form-item>
              <el-checkbox v-model="remember">记住我</el-checkbox>
            </el-form-item>

            <!-- 登录按钮，带动效 -->
            <el-form-item>
              <el-button class="login-btn" type="primary" :loading="loading" @click="onLogin">登录</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </section>
    </div>
  </div>
</template>

<script setup>
// 登录页：品牌区+半透明表单，调用登录接口，包含前端验证码校验
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from '../api/auth'
import { User, Lock, Cherry } from '@element-plus/icons-vue'

const router = useRouter()
const formRef = ref()
const form = reactive({ username: '', password: '', captchaInput: '' })
const loading = ref(false)
const remember = ref(true)
// 前端生成验证码：使用 Canvas 绘制并校验（示例，后端校验时也会传递 captcha 字段）
const captchaRef = ref(null)
const captchaCode = ref('')

// 表单基础校验：用户名/密码必填
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  captchaInput: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

// 生成随机验证码并绘制到 Canvas（含噪点与扰动线，增强识别质感）
function generateCode(len = 4){
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
  let code = ''
  for(let i=0; i<len; i++) code += chars[Math.floor(Math.random()*chars.length)]
  return code
}

function drawCaptcha(){
  const canvas = captchaRef.value
  if(!canvas) return
  const ctx = canvas.getContext('2d')
  const w = canvas.width, h = canvas.height
  // 背景渐变
  const grad = ctx.createLinearGradient(0,0,w,h)
  grad.addColorStop(0, '#eef2f7')
  grad.addColorStop(1, '#dbe5f1')
  ctx.fillStyle = grad
  ctx.fillRect(0,0,w,h)
  // 文本
  ctx.font = 'bold 22px Segoe UI, Arial'
  ctx.fillStyle = '#3a4a66'
  ctx.textBaseline = 'middle'
  const code = captchaCode.value
  for(let i=0;i<code.length;i++){
    const x = 20 + i*24
    const y = h/2 + (Math.random()*6-3)
    const angle = (Math.random()*0.4 - 0.2)
    ctx.save()
    ctx.translate(x,y)
    ctx.rotate(angle)
    ctx.fillText(code[i], 0, 0)
    ctx.restore()
  }
  // 扰动线
  for(let i=0;i<2;i++){
    ctx.strokeStyle = i===0 ? '#9db7d6' : '#c2d1e2'
    ctx.beginPath()
    ctx.moveTo(Math.random()*w, Math.random()*h)
    ctx.bezierCurveTo(Math.random()*w, Math.random()*h, Math.random()*w, Math.random()*h, Math.random()*w, Math.random()*h)
    ctx.stroke()
  }
  // 噪点
  for(let i=0;i<30;i++){
    ctx.fillStyle = '#b9c9dc'
    ctx.beginPath()
    ctx.arc(Math.random()*w, Math.random()*h, 1, 0, Math.PI*2)
    ctx.fill()
  }
}

function refreshCaptcha(){
  captchaCode.value = generateCode(4)
  drawCaptcha()
}

onMounted(refreshCaptcha)

async function onLogin(){
  formRef.value.validate(async (ok) => {
    if(!ok) return
    // 前端先校验验证码是否匹配
    if(form.captchaInput.trim().toUpperCase() !== captchaCode.value){
      ElMessage.error('验证码错误，请重试')
      refreshCaptcha()
      return
    }
    loading.value = true
    try {
      const res = await login({ username: form.username, password: form.password, captcha: form.captchaInput })
      if(res.code === 200 && res.data){
        // 按是否“记住我”选择存储位置
        const storage = remember.value ? localStorage : sessionStorage
        storage.setItem('token', res.data.token)
        storage.setItem('username', res.data.username)
        storage.setItem('userId', String(res.data.userId))
        ElMessage.success(res.message || '登录成功')
        router.replace('/categories')
      } else {
        ElMessage.error(res.message || '登录失败')
        refreshCaptcha()
      }
    } catch (e) {
      ElMessage.error('登录失败：请检查网络或账号信息')
      refreshCaptcha()
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
/* 背景采用柔和自然风景，伪元素叠加模糊+透明层，保证表单可读性 */
.login-bg {
  position: relative;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background: #f5f7fa;
}
.login-bg::before {
  content: '';
  position: absolute;
  inset: 0;
  background: url('https://images.unsplash.com/photo-1501785888041-af3ef285b470?q=80&w=1920&auto=format&fit=crop') center/cover no-repeat;
  filter: blur(6px);
  opacity: 0.65;
  transform: scale(1.06); /* 防止模糊边缘露出 */
}
.login-bg::after {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(135deg, rgba(255,255,255,0.75), rgba(245,247,250,0.75));
}
.login-wrap { position: relative; z-index: 1; width: 100%; max-width: 1080px; display: grid; grid-template-columns: 1.1fr 1fr; gap: 24px; padding: 24px; }

/* 左侧品牌区域 */
.branding { color: #1f2d3d; padding: 24px; backdrop-filter: blur(2px); }
.brand-logo { display: flex; align-items: center; gap: 12px; }
.logo-icon { font-size: 36px; color: #409EFF; }
.brand-name { font-size: 24px; font-weight: 700; }
.brand-desc { margin: 8px 0 16px; font-size: 16px; color: #506176; }
.tech-tags { display: flex; gap: 8px; flex-wrap: wrap; }

/* 右侧半透明表单卡片 */
.form-area { display: flex; align-items: center; }
.login-card { width: 100%; background: rgba(255,255,255,0.9); border-radius: 12px; box-shadow: 0 8px 24px rgba(31,45,61,0.18); }
.title { margin: 0 0 16px; text-align: center; color: #1f2d3d; }

/* 验证码行 */
.captcha-row { display: flex; align-items: center; gap: 8px; }
.captcha-canvas { cursor: pointer; border-radius: 6px; border: 1px solid #e4e7ed; }

/* 登录按钮动效 */
.login-btn { width: 100%; transition: all .2s ease; box-shadow: 0 2px 6px rgba(64,158,255,0.45); }
.login-btn:hover { transform: translateY(-1px); box-shadow: 0 6px 16px rgba(64,158,255,0.35); }
.login-btn:active { transform: translateY(0); box-shadow: 0 3px 10px rgba(64,158,255,0.4); }

/* 响应式适配 */
@media (max-width: 960px) {
  .login-wrap { grid-template-columns: 1fr; }
  .branding { text-align: center; }
  .brand-logo { justify-content: center; }
}
</style>